package com.threefish.common.plugins.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.crypto.hash.Sha256Hash;

import java.security.MessageDigest;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/11
 */
public class Sha256HashCredentialsMatcher extends CodecSupport implements CredentialsMatcher {
    /**
     * Returns {@code true} if the provided token credentials match the stored account credentials,
     * {@code false} otherwise.
     *
     * @param token the {@code AuthenticationToken} submitted during the authentication attempt
     * @param info  the {@code AuthenticationInfo} stored in the system.
     * @return {@code true} if the provided token credentials match the stored account credentials,
     * {@code false} otherwise.
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        ShiroUserToken userToken = (ShiroUserToken) token;
        if (userToken.needVerifyPass()) {
            Sha256Hash sha = new Sha256Hash(info.getCredentials(), ((SimpleAuthenticationInfo) info).getCredentialsSalt());
            byte[] tokenBytes = toBytes(userToken.getCredentials());
            byte[] accountBytes = toBytes(sha.toHex());
            return MessageDigest.isEqual(tokenBytes, accountBytes);
        } else {
            return true;
        }
    }
}
